package com.roncoo.education.db.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.roncoo.education.api.request.NewsCategoryRequest;
import com.roncoo.education.db.dao.NewsCategoryDao;
import com.roncoo.education.db.entity.NewsCategory;
import com.roncoo.education.util.FileService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class NewsCategoryService {

    @Resource
    NewsCategoryDao newsCategoryDao;

    @Resource
    FileService fileService;

    public Map<String,String> saveNewsCategory(NewsCategoryRequest req){
        NewsCategory category = BeanUtil.copyProperties(req, NewsCategory.class);
        Integer pid = 0;
        if(category.getId()!=null){
            NewsCategory oldCate = newsCategoryDao.findById(category.getId());
            if(oldCate!=null){
                if(category.getImgUrl()!=null && !category.getImgUrl().equals(oldCate.getImgUrl())){
                    //删除旧图文件
                    if(StrUtil.isNotBlank(oldCate.getImgUrl())) {
                        fileService.deleteFileByUrl(oldCate.getImgUrl());
                    }
                }
            }
            pid = category.getId();
            newsCategoryDao.updateById(category);
        }else{
            category.setDelFlag(1);
            newsCategoryDao.insert(category);
            pid = category.getId();
        }
        Map<String,String> ret = new HashMap<>();
        ret.put("isError", "success");
        ret.put("id", String.valueOf(pid));
        ret.put("code", "1");
        return ret;
    }

    public List<NewsCategory> findByBean(NewsCategory news){
        return newsCategoryDao.findByBean(news);
    }
}
